package org.bee.controller;

import org.bee.PageUtil;
import org.bee.ResultTool;
import org.bee.enums.IsDelete;
import org.bee.enums.ResultCode;
import org.bee.exception.ExceptionUtils;
import org.bee.id.UUIDUtils;
import org.bee.input.DictInsertVo;
import org.bee.input.DictSearchVo;
import org.bee.input.DictSelectVo;
import org.bee.input.DictUpdateVo;
import org.bee.model.Dict;
import org.bee.model.DictSelect;
import org.bee.model.result.Result;
import org.bee.output.DictOut;
import org.bee.secuirty.annotation.ApiAuth;
import org.bee.secuirty.context.CurrentUser;
import org.bee.service.DictService;
import org.bee.service.ext.DictExtService;
import org.bee.transaction.TransUtils;
import org.bee.transaction.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 字典表控制器
 */
@RestController
@RequestMapping("/dict")
public class DictController {
    Logger logger = LoggerFactory.getLogger(DictController.class);

    private final DictService dictService;
    private final DictExtService dictExtService;

    public DictController(DictService dictService,
                          DictExtService dictExtService) {
        this.dictService = dictService;
        this.dictExtService = dictExtService;
    }

    /**
     * 新增字典表
     * @param dictInsertVo 新增参数
     * @return 新增结果
     */
    @PostMapping("insert")
    @ApiAuth(value = "dict.insert",description = "字典新增")
    public Result insert(@RequestBody DictInsertVo dictInsertVo) {
        Result result = ResultTool.success();
        List<Dict> select = dictExtService.selectDict(dictInsertVo.getDictCode());
        if(!select.isEmpty()){
            result = ResultTool.fail(ResultCode.DATA_REPEAT);
            result.setMsg("字典编码重复");
            return result;
        }
        Transaction trans = null;
        try {
            Dict dict = new Dict();
            BeanUtils.copyProperties(dictInsertVo, dict);
            dict.setId(UUIDUtils.simpleUuid());
            dict.setCreateUser(CurrentUser.getUser().getUserId());
            dict.setCreateTime(new Date());
            dict.setIsDeleted(Boolean.valueOf(IsDelete.FALSE.getCode()));
            trans= TransUtils.getTrans();
            trans.begin();
            dictService.insert(dict);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 删除字典表
     * @param id id
     * @return 删除结果
     */
    @DeleteMapping("delete")
    @ApiAuth(value = "dict.delete",description = "字典删除")
    public Result delete(@RequestParam("id") String id) {
        Result result = ResultTool.success();
        Transaction trans = null;
        if (id == null|| id.isEmpty()) {
            result = ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
            return result;
        }
        try {
            trans= TransUtils.getTrans();
            trans.begin();
            dictService.delete(id,false);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 修改字典表
     * @param dictUpdateVo 修改参数
     * @return 修改结果
     */
    @PostMapping("update")
    @ApiAuth(value = "dict.update",description = "字典修改")
    public Result update(@RequestBody DictUpdateVo dictUpdateVo) {
        Result result = ResultTool.success();
        Transaction trans = null;
        try {
            Dict dict = new Dict();
            BeanUtils.copyProperties(dictUpdateVo, dict);
            dict.setUpdateUser(CurrentUser.getUser().getUserId());
            dict.setUpdateTime(new Date());
            trans= TransUtils.getTrans();
            trans.begin();
            dictService.update(dict);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 分页查询字典表
     * @param dictSearchVo 查询参数
     * @return 查询结果
     */
    @PostMapping("pageQuery")
    @ApiAuth(value = "dict.pageQuery",description = "字典分页查询")
    public Result select(@RequestBody DictSearchVo dictSearchVo) {
        Result result = ResultTool.success();
        PageUtil.setPage(dictSearchVo.getCurrent(),dictSearchVo.getSize());
        List<Dict> select = dictService.select(dictSearchVo);
        List<DictOut> selectOut = new ArrayList<>();
        select.forEach(dict -> {
            DictOut dictOut = new DictOut();
            BeanUtils.copyProperties(dict, dictOut);
            selectOut.add(dictOut);
        });
        result.setPageData(selectOut);
        return result;
    }

    /**
     * 获取字典详情
     * @param dictSelectVo 查询参数
     * @return 查询结果
     */
    @PostMapping("getDicts")
    @ApiAuth(value = "dict.getDicts",description = "字典详情")
    public Result getDicts(@RequestBody DictSelectVo dictSelectVo) {
        Result result = ResultTool.success();
        if(dictSelectVo == null){
            result = ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
            return result;
        }
        if(dictSelectVo.getDictCode() == null || dictSelectVo.getDictCode().isEmpty()){
            result = ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
            result.setMsg("字典编码不能为空");
            return result;
        }
        List<Dict> select = dictExtService.selectDict(dictSelectVo.getDictCode());
        if(select.isEmpty()){
            result = ResultTool.fail(ResultCode.DATA_NULL);
            result.setMsg(dictSelectVo.getDictCode()+"字典不存在");
            return result;
        }
        Dict first = select.getFirst();
        if(null!=dictSelectVo.getConditions()){
            first.setConditions(dictSelectVo.getConditions());
        }
        if(dictSelectVo.getCurrent()==0&&dictSelectVo.getSize()==0){
                dictSelectVo.setCurrent(0);
                dictSelectVo.setSize(1000);
        }
        PageUtil.setPage(dictSelectVo.getCurrent(),dictSelectVo.getSize());
        List<DictSelect> dictSelects = null;
        try {
            dictSelects = dictExtService.getDictDetails(first, dictSelectVo.getLabel(),
                    dictSelectVo.getValue());
        } catch (Exception e) {
            result = ResultTool.fail();
            result.setMsg("字典执行异常,请检查配置是否正确");
            return result;
        }
        result.setPageData(dictSelects);
        return result;
    }

    /**
     * 根据id查询字典
     * @param id id
     * @return 字典信息
     */
    @GetMapping("selectById")
    @ApiAuth(value = "dict.selectById",description = "字典根据id查询")
    public Result getDictByCode(String id){
        Result result = ResultTool.success();
        if(id == null || id.isEmpty()){
            result = ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
            result.setMsg("字典id不能为空");
            return result;
        }
        Dict select = dictService.selectById(id);
        result.setData(select);
        return result;
    }
}
